<?php

namespace app\api\service\wanlshop;

use app\api\model\wanlshop\ShopSort;
use think\Log;
use app\api\model\wanlshop\Brand;
use app\api\model\wanlshop\Category;
use app\api\model\wanlshop\Goods as GoodsModel;
use app\api\model\wanlshop\GoodsSpu;
use app\api\model\wanlshop\GoodsSku;
use app\api\model\wanlshop\OrderGoods;
use app\api\model\WpsGoods;
use app\api\model\WpsGoodsSku;
use think\Db;
use think\Exception;
use think\Model;

class Goods extends Model
{
    // 商品model
    protected $goodsModel = null;

    public function __construct($data = [])
    {
        Log::record('123');
        parent::__construct($data);
        $this->goodsModel = new GoodsModel();

    }

    /**
     *  添加第三方商品到数据表
     */

    public function insGoods($data, $output = false, $page = false, $size = false)
    {
        // 数据
        foreach ($data as $key => $val) {
            $this->singleHandle($key, $val, $output, $page, $size);
        }

        return true;
    }

    public function singleHandle($key, $val, $output = false, $page = false, $size = false)
    {
        $multi = self::getBuybackMultiple();
        $starttime = microtime(true);
        Db::startTrans();
        try {
            //todo 唯品尚商品shop_id置为10，暂定
            //品牌查询
            //新增商品数据
            //给客户的价格我们用吊牌价，若吊牌价大于进价的2.1倍，则划去，写进价的2.1倍价格
//            $price = ($val['c_original_price'] > ($val['c_in_price'] * 2.1)) ? ($val['c_in_price'] * 2.1) : $val['c_original_price'];
            $price = $val['c_in_price'] * $multi;

            $s = strtotime($val['c_start_datetime']);
            $e = strtotime($val['c_stop_datetime']);
            $category = Category::where('c_code', $val["c_class_id"])->find();
            $goodsData = [
                "category_id" => $category['id'],
                "shop_category_id" => ShopSort::where('name', $category['name'])->value('id'),
                "title" => $val["c_goods_name"],
                "image" => $val["c_goods_image"],
                "brand_id" => Brand::where('c_id', $val["c_brand_id"])->value('id', 0),
                "description" => $val["c_goods_description"],
                "content" => $val["c_specifications"],
                "grounding" => isset($val["state"]) ?? 1,
                "c_id" => $val["c_id"],
                "c_father_goods_id" => $val["c_father_goods_id"],
                "c_no_delivery_area" => $val["c_no_delivery_area"],
                "price" => $price,
                "original_price" => $val["c_original_price"],
                "c_in_price" => $val["c_in_price"],
                "c_original_price" => $val["c_original_price"],
                "c_specifications" => $val["c_specifications"],
                "c_brand_name" => $val["c_brand_name"],
                "profit" => $val["profit"] ?? '',
                "platform" => $this->goodsModel->platformOfArray[1],
                "shop_id" => 10,
                'is_tj' => mt_rand(0, 1),
                'is_hg' => 1,
                'is_new' => mt_rand(0, 1),
                'integral' => floor($price),
                "c_goods_stock_valid" => $val["c_goods_stock_valid"],
                "c_goods_stock_start" => $val["c_goods_stock_start"],
                'status' => (time() <= $s || time() >= $e || $val["is_show"] == 0) ? 'hidden' : 'normal',
            ];

            $type = '更新';
            $goods = GoodsModel::where('c_id', $val["c_id"])->find();
            if (!$goods) {
                $type = '新增';
                $goods = new GoodsModel();
                $goods->data($goodsData);
                $goods->save();
            } else {
                $goods->save($goodsData);
            }

            //新增sku数据
            $goods_id = $goods->id;

            /*$specifications = $val["c_specifications"];
            $difference = '';
            if ($specifications) {
                $specifications = array_filter(explode(' ', str_replace(["\n", "\r", "\t"], ' ', $specifications)));
                foreach ($specifications as $item) {
                    $v = explode(':', str_replace('：', ':', $item));
                    $difference .= isset($v[1]) ? $v[1] . ',' : $v[0];
                }
            }

            $difference = rtrim($difference, ',');
            $sku = GoodsSku::where(['goods_id' => $goods_id, 'difference' => $difference ?: '默认规格'])->find();*/
            $goodsSkus = Common::getData('getGoodsDetails', ['father_id' => $val["c_father_goods_id"]]);
            if (!empty($goodsSkus['goods_sku'])) {
                foreach ($goodsSkus['goods_sku'] as $k => $item) {
                    $e = $item['c_goods_color'] . ',' . $item['c_goods_size'];
                    //给客户的价格我们用吊牌价，若吊牌价大于进价的2.1倍，则划去，写进价的2.1倍价格
//                    $price = ($item['c_original_price'] > ($item['c_in_price'] * 2.1)) ? ($item['c_in_price'] * 2.1) : $item['c_original_price'];
                    $price = $item['c_in_price'] * $multi;
                    $sku = GoodsSku::where(['goods_id' => $goods_id, 'difference' => $e])->find();
                    if (!$sku) {
                        $sku = new GoodsSku();
                    }
                    $sku->data([
                        'goods_id' => $goods_id,
                        'thumbnail' => $item['c_goods_image'],
                        'difference' => $e,
                        'price' => $price,
                        'market_price' => $item['c_original_price'],
                        'stock' => $item['c_goods_stock_valid'],
                        'weigh' => 0,
                        'sn' => $item['c_goods_id'],
                        'sales' => 0,
                        'state' => 0,
                        'wps_goods_id' => $item['c_goods_id'] ?? '',
                        'wps_father_goods_id' => $item['c_father_goods_id'] ?? '',
                        'c_in_price' => $item['c_in_price'] ?? 0,
                    ]);
                    $sku->save();

                    $t = $k + 1;
                    $output->writeln("id:$t,属性：{$item['c_goods_color']},规格:{$item['c_goods_size']},价格:{$price},库存:{$item['c_goods_stock_valid']}");
                }

                $spuData = [
                    'goods_id' => $goods_id,
                    'name' => '属性',
                    'item' => implode(',', array_unique(array_column($goodsSkus['goods_sku'], 'c_goods_color')))
                ];
                $spu = GoodsSpu::where($spuData)->find();
                if (!$spu) {
                    $spu = new GoodsSpu();
                }
                $spu->data($spuData);
                $spu->save();

                $spuData = [
                    'goods_id' => $goods_id,
                    'name' => '规格',
                    'item' => implode(',', array_unique(array_column($goodsSkus['goods_sku'], 'c_goods_size')))
                ];
                $spu = GoodsSpu::where($spuData)->find();
                if (!$spu) {
                    $spu = new GoodsSpu();
                }
                $spu->data($spuData);
                $spu->save();
            }

            /*if (!$sku) {
                $sku = new GoodsSku();
            }
            $sku->data([
                'goods_id' => $goods_id,
                'thumbnail' => $goodsSkus['goods_sku'][0]['c_goods_image'] ?? '',
                'difference' => $difference ?: '默认规格',
                'price' => $price,
                'market_price' => $val['c_original_price'],
                'stock' => $val['c_goods_stock_valid'],
                'weigh' => 0,
                'sn' => $val['c_company_code'],
                'sales' => 0,
                'state' => 0,
            ]);
            $sku->save();*/

            //新增wps_goods、wps_sku数据
            WpsGoods::where(['wanlshop_goods_id' => $goods_id])->delete();
            WpsGoodsSku::where(['wanlshop_goods_id' => $goods_id])->delete();
            if ($goodsSkus) {
                WpsGoods::insertData(array_merge($val, [
                    'wanlshop_goods_id' => $goods_id,
                    'c_sale_price' => bcmul($val['c_in_price'], $multi, 2)
                ]));
                $skus = $goodsSkus['goods_sku'];
                WpsGoodsSku::insertData(array_map(function ($item) use ($goods_id, $val) {
                    return array_merge([
                        'wanlshop_goods_id' => $goods_id,
                        'c_specifications' => $val["c_specifications"],
                        'c_company_code' => $val['c_company_code'],
                        'c_id' => $val['c_id'],
                    ], $item);
                }, $skus));
            }
            $goods->images = str_replace(';', ',', $goodsSkus['c_banner_images'] ?? '');
            $goods->content = $goodsSkus['c_goods_content'] ?? '';
            $goods->save();

            $orderGoods = OrderGoods::where('goods_id', $goods_id)->find();

            if ($orderGoods) {
                $orderGoods->image = $goods->image;
                $orderGoods->save();
            }

            //新增spu数据
            /*if ($specifications) {
                foreach ($specifications as $item) {
                    $v = explode(':', str_replace('：', ':', $item));
                    $spuData = [
                        'goods_id' => $goods_id,
                        'name' => $v[0],
                        'item' => $v[1] ?? $v[0]
                    ];
                    if ($spuData) {
                        $output->writeln(json_encode($specifications, JSON_UNESCAPED_UNICODE));
                        $output->writeln(json_encode($spuData, JSON_UNESCAPED_UNICODE));
                    }
                    $spu = GoodsSpu::where($spuData)->find();
                    if (!$spu) {
                        $spu = new GoodsSpu();
                    }
                    $spu->data($spuData);
                    $spu->save();
                }
            } else {
                $spuData = [
                    'goods_id' => $goods_id,
                    'name' => '规格',
                    'item' => '默认规格'
                ];
                $spu = GoodsSpu::where($spuData)->find();
                if (!$spu) {
                    $spu = new GoodsSpu();
                }
                $spu->data($spuData);
                $spu->save();
            }*/

            if ($output) {
                $k = $key + 1;
                $endtime = microtime(true);
                $ex = number_format($endtime - $starttime, 4);
                $total = ($page - 1) * $size + $k;
                $output->writeln("「 $type 」 第 {$page} 页第 {$k} 条数据成功,id:$goods_id,c_id:{$val['c_id']},title:{$val["c_goods_name"]},耗时:$ex 秒,总条数:$total");
            }
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            throw new Exception("操作数据失败,message:" . $e->getMessage() . ",Line:" . $e->getLine(), 4);
        }
        return true;
    }

    public static function getBuybackMultiple()
    {
        $config = get_addon_config('wanlshop');
        $config = $config['gift'];
        return $config['mulriple'] ?? 0;
    }
}
